import React from 'react';
import {connect} from 'react-redux';
import { List, Badge } from 'antd-mobile';

@connect(
	state => state
)
export default class Msg extends React.Component {
	getLast(arr) {
		return arr[arr.length-1];
	}
	render() {
		const Item = List.Item;
		const Brief = Item.Brief;
		// 当前登录的用户id
		const userId = this.props.user._id;
		const userInfo = this.props.chat.users;
		const msgGroup = {};

		// 根据chatid划分对话组
		this.props.chat.chatmsg.forEach((v) => {
			msgGroup[v.chatid] = msgGroup[v.chatid] || [];
			msgGroup[v.chatid].push(v);
		});

		console.log('group:', msgGroup)
		console.log('obj', Object.values(msgGroup))

		// 找出所有对话中的最后说话的一组对话记录
		const chatList = Object.values(msgGroup).sort((a, b) => {
			const lastA = this.getLast(a).create_time;
			const lastB = this.getLast(b).create_time;
			return lastB - lastA;
		});

		return (
			<List>
				{chatList.map(v => {
					// 拿出最后一组对话记录里的最新一条
					const lastItem = this.getLast(v);
					const targetId = v[0].from === userId ? v[0].to : v[0].from;			
					const unread = v.filter((v) => !v.read && v.to === userId).length;		
					return (
						<Item
							extra={<Badge text={unread} ></Badge>}
							key={lastItem._id}
							thumb={require(`../img/${userInfo[targetId].avatar}.png`)}
							arrow="horizontal"
							onClick={() => {
								this.props.history.push(`/chat/${targetId}`);
							}}
						>
							{lastItem.content}
							<Brief>{userInfo[targetId].name}</Brief>
						</Item>
					)
				})}
			</List>
		)
	}
}